﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		UserRepository.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 //   File:            UserRepository.cs
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using Dexter.Core.Data.Repository;
using Dexter.Domain.Model;
using Dexter.Domain.Results;
using Dexter.Logger.Contracts;
using Dexter.Repository.NHibernate.Queries;
using NHibernate;
using NHibernate.Criterion;
using NHibernate.Transform;
using Topics.Radical.Validation;
using ISessionFactory = Dexter.Repository.NHibernate.SessionFactory.ISessionFactory;

namespace Dexter.Repository.NHibernate.Repositories {
	
	/// <summary>
	/// The implementation of <see cref="IUserRepository"/>.
	/// </summary>
	/// <example>The following is an example of initializing 
	///          an <c>UserRepository</c> type:
	///   <code>
	///       // Create the type.
	///       UserRepository ds = new UserRepository;
	/// 
	///       if ( null == ds )
	///           return;
	/// 
	///       return ds.DoSomething( 5 );
	///   </code>
	/// </example>
	public class UserRepository : RepositoryBase <User> , IUserRepository {
		
		/// <summary>
		/// Initializes a new instance of the <see cref="UserRepository"/> class.
		/// </summary>
		/// <param name="sessionFactory">The session factory.</param>
		/// <param name="logger">The logger.</param>
		public UserRepository ( ISessionFactory sessionFactory , ILogger logger ) : base ( sessionFactory , logger ) {}

		#region Implementation of IUserRepository

		/// <summary>
		/// Saves the specified user into the repository.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Save ( User item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid user" );

			item.ValidateForSave ( );

			base.Add ( item );
		}

		/// <summary>
		/// Updates the specified user into the repository.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Update ( User item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid user" );

			item.ValidateForUpdate ( );

			Session.Update ( item );
		}

		/// <summary>
		/// Deletes the specified user into the repository.
		/// </summary>
		/// <param name="item">The item.</param>
		/// <exception cref="ArgumentNullException"> If <paramref name="item"/> is <c>null</c>.</exception>
		public virtual void Delete ( User item ) {
			Ensure.That ( item )
				.Named ( "item" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid user" );

			item.ValidateForDelete ( );

			base.Remove ( item );
		}

		/// <summary>
		/// Gets a user with roles fetched by his key.
		/// </summary>
		/// <param name="key">The key.</param>
		/// <returns></returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="key"/> is lesser than 1.</exception>
		public virtual User GetByKeyWithRoles ( int key ) {
			return GetByKeyWithRoles ( key , true );
		}

		/// <summary>
		/// Gets a user with roles fetched by his key.
		/// </summary>
		/// <param name="key">The key of hte user.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns></returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="key"/> is lesser than 1.</exception>
		public virtual User GetByKeyWithRoles ( int key, bool enableTracking ) {
			Ensure.That ( key )
				.Named ( "key" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid user key" );

			return Session.GetNamedQuery ( KnownQueries.UserRepository.GetByKeyWithRoles )
				.SetParameter ( "key" , key )
				.SetReadOnly ( !enableTracking )
				.UniqueResult <User> ( );
		}

		/// <summary>
		/// Gets a user with roles fetched by his email.
		/// </summary>
		/// <param name="email">The email of the user.</param>
		/// <returns>
		/// An instane of <see cref="User"/> or null if the user will not exist.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="email"/> is <c>null</c>.</exception>
		public virtual User GetByEmailWithRoles ( MailAddress email ) {
			return GetByEmailWithRoles ( email , true );
		}

		/// <summary>
		/// Gets a user with roles fetched by his email.
		/// </summary>
		/// <param name="email">The email of the user.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instane of <see cref="User"/> or null if the user will not exist.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="email"/> is <c>null</c>.</exception>
		public virtual User GetByEmailWithRoles ( MailAddress email, bool enableTracking )
		{
			Ensure.That ( email )
				.Named ( "email" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNull ( )
				.WithMessage ( "Invalid email." );

			return Session.GetNamedQuery ( KnownQueries.UserRepository.GetByEmailWithRoles )
				.SetParameter ( "email" , email.Address )
				.SetReadOnly ( !enableTracking )
				.UniqueResult <User> ( );
		}

		/// <summary>
		/// Gets a user with roles fetched by his username.
		/// </summary>
		/// <param name="username">The username of the user.</param>
		/// <returns>
		/// An instane of <see cref="User"/> or null if the user will not exist.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="username"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual User GetByUsernameWithRoles ( string username ) {
			return GetByUsernameWithRoles ( username , true );
		}

		/// <summary>
		/// Gets a user with roles fetched by his username.
		/// </summary>
		/// <param name="username">The username of the user.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An instane of <see cref="User"/> or null if the user will not exist.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="username"/> is <c>null</c> or <c>empty</c>.</exception>
		public virtual User GetByUsernameWithRoles ( string username, bool enableTracking ) {
			Ensure.That ( username )
				.Named ( "username" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNullNorEmpty ( )
				.WithMessage ( "Invalid username." );

			return Session.GetNamedQuery ( KnownQueries.UserRepository.GetByUsernameWithRoles )
				.SetParameter ( "username" , username )
				.SetReadOnly ( !enableTracking )
				.UniqueResult <User> ( );
		}

		/// <summary>
		/// Retrieve a list of users with all roles fetched.
		/// </summary>
		/// <param name="pageIndex">Index of the page.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<User> GetListOfUserWithRoles ( int pageIndex, int pageSize ) {
			return GetListOfUserWithRoles ( pageIndex , pageSize , true );
		}

		/// <summary>
		/// Retrieve a list of users with all roles fetched.
		/// </summary>
		/// <param name="pageIndex">Index of the page.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<User> GetListOfUserWithRoles ( int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.UserRepository.GetListOfUserWithRolesCount )
				.FutureValue <long> ( );

			var detached = QueryOver.Of<User> ( )
				.Select ( x => x.Id )
				.Take ( pageSize )
				.Skip ( pageIndex * pageSize );

			IEnumerable<User> result = Session.QueryOver<User> ( )
				.WithSubquery.WhereProperty ( x => x.Id ).In ( detached )
				.Fetch ( x => x.Roles ).Eager
				.TransformUsing ( Transformers.DistinctRootEntity )
				.Future<User> ( );

			return new PagedResult<User> ( pageIndex, pageSize, result.ToList ( ), total.Value );
		}

		/// <summary>
		/// Retrieve a list of users with all roles fetched where the username match (%usernameToMatch%) with the passed value.
		/// </summary>
		/// <param name="usernameToMatch">The part of the username.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="usernameToMatch"/> is <c>null</c> or <c>empty</c>.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<User> FindUsersByNameWithRoles ( string usernameToMatch, int pageIndex, int pageSize ) {
			return FindUsersByNameWithRoles ( usernameToMatch , pageIndex , pageSize , true );
		}

		/// <summary>
		/// Retrieve a list of users with all roles fetched where the username match (%usernameToMatch%) with the passed value.
		/// </summary>
		/// <param name="usernameToMatch">The part of the username.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="usernameToMatch"/> is <c>null</c> or <c>empty</c>.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<User> FindUsersByNameWithRoles ( string usernameToMatch, int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			Ensure.That ( usernameToMatch )
				.Named ( "usernameToMatch" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNullNorEmpty ( )
				.WithMessage ( "Invalid username to match." );

			usernameToMatch = string.Format ( "%{0}%" , usernameToMatch );

			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.UserRepository.FindUsersByNameWithRolesCount )
				.SetParameter ( "loweredUsername" , usernameToMatch )
				.FutureValue <long> ( );

			IEnumerable <User> result = Session.GetNamedQuery ( KnownQueries.UserRepository.FindUsersByNameWithRoles )
				.SetParameter ( "loweredUsername" , usernameToMatch )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future <User> ( );

			return new PagedResult<User>(pageIndex, pageSize, result.ToList(), total.Value);
		}

		/// <summary>
		/// Retrieve a list of users with all roles fetched where the email match (%emailToMatch%) with the passed value.
		/// </summary>
		/// <param name="emailToMatch">The part of the email.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="emailToMatch"/> is <c>null</c> or <c>empty</c>.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<User> FindUsersByEmailWithRoles ( string emailToMatch, int pageIndex, int pageSize ) {
			return FindUsersByEmailWithRoles ( emailToMatch , pageIndex , pageSize , true );
		}

		/// <summary>
		/// Retrieve a list of users with all roles fetched where the email match (%emailToMatch%) with the passed value.
		/// </summary>
		/// <param name="emailToMatch">The part of the email.</param>
		/// <param name="pageIndex">Index of the page.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		/// <returns>
		/// An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.
		/// </returns>
		/// <exception cref="ArgumentNullException"> If <paramref name="emailToMatch"/> is <c>null</c> or <c>empty</c>.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public virtual IPagedResult<User> FindUsersByEmailWithRoles ( string emailToMatch, int pageIndex, int pageSize, bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 , Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			Ensure.That ( emailToMatch )
				.Named ( "emailToMatch" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsNotNullNorEmpty ( )
				.WithMessage ( "Invalid email to match." );

			emailToMatch = string.Format ( "%{0}%" , emailToMatch );

			IFutureValue <long> total = Session.GetNamedQuery ( KnownQueries.UserRepository.FindUsersByNameWithRolesCount )
				.SetParameter ( "loweredEmail" , emailToMatch )
				.FutureValue <long> ( );

			IEnumerable <User> result = Session.GetNamedQuery ( KnownQueries.UserRepository.FindUsersByNameWithRoles )
				.SetParameter ( "loweredEmail" , emailToMatch )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future <User> ( );

			return new PagedResult<User>(pageIndex, pageSize, result.ToList(), total.Value);
		}

		/// <summary>
		/// Return the number of users online in the specified window time.
		/// </summary>
		/// <param name="userIsOnlineTimeWindow">The user is online time window.</param>
		/// <returns>The numbers of users online.</returns>
		/// <exception cref="ArgumentOutOfRangeException">Will be throw if the 'userIsOnlineTimeWindow' will be lesser than 1.</exception>
		/// <exception cref="ArgumentOutOfRangeException"> If <paramref name="userIsOnlineTimeWindow"/> is lesser than 1.</exception>
		public virtual int GetOnlineUsers ( int userIsOnlineTimeWindow ) {
			Ensure.That ( userIsOnlineTimeWindow )
				.Named ( "userIsOnlineTimeWindow" )
				.WithPreview ( ( v , e ) => Logger.Warn ( v.GetFullErrorMessage ( ) , e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid user is online time window." );

			var span = new TimeSpan ( 0 , userIsOnlineTimeWindow , 0 );
			DateTime time = DateTime.Now.Subtract ( span );

			return Session.GetNamedQuery ( KnownQueries.UserRepository.GetByUsernameWithRoles )
				.SetParameter ( "lastActivityDate" , time )
				.UniqueResult <int> ( );
		}

		/// <summary>
		/// Retrieve a list all roles.
		/// </summary>
		///<param name="pageIndex">Index of the page.</param>
		/// <param name="pageSize">Size of the page.</param>
		/// <param name="enableTracking">if set to <c>true</c> the tracking system of the return object will be enable.</param>
		///<returns>An concrete implementation of <see cref="IPagedResult{T}"/>. The result will never be null.</returns>
		///<exception cref="ArgumentOutOfRangeException"> If <paramref name="pageIndex"/> is lesser than 0.</exception>
		///<exception cref="ArgumentOutOfRangeException"> If <paramref name="pageSize"/> is lesser than 1.</exception>
		public IPagedResult <Role> GetAllRoles ( int pageIndex , int pageSize , bool enableTracking ) {
			Ensure.That ( pageIndex )
				.Named ( "pageIndex" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0, Or.Equal )
				.WithMessage ( "Invalid page index." );

			Ensure.That ( pageSize )
				.Named ( "pageSize" )
				.WithPreview ( ( v, e ) => Logger.Warn ( v.GetFullErrorMessage ( ), e ) )
				.IsGreaterThen ( 0 )
				.WithMessage ( "Invalid page size." );

			IFutureValue<long> total = Session.GetNamedQuery ( KnownQueries.UserRepository.GetAllRolesCount )
				.FutureValue<long> ( );

			IEnumerable<Role> result = Session.GetNamedQuery ( KnownQueries.UserRepository.GetAllRoles )
				.SetFirstResult ( pageIndex * pageSize )
				.SetMaxResults ( pageSize )
				.SetReadOnly ( !enableTracking )
				.Future<Role> ( );

			return new PagedResult<Role> ( pageIndex, pageSize, result.ToList ( ), total.Value );
		}

		#endregion
	}
}
